package com.google.code.coma.space;

import com.google.code.coma.domain.Order;
import org.mozartspaces.capi3.Capi3Exception;
import org.mozartspaces.capi3.CountNotMetException;
import org.mozartspaces.capi3.javanative.operation.NativeEntry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 */
public class OrderSelectorCallback implements SelectorCallback {
    private Order idTemplate;

    public OrderSelectorCallback(Order idTemplate) {
        this.idTemplate = idTemplate;
    }

    @Override
    public List<NativeEntry> doInTransaction(Collection<NativeEntry> coordinatorCollection, CallContext callContext) throws Capi3Exception {
        if (idTemplate != null) {
            return selectByIdTemplate(coordinatorCollection, callContext);
        }

        return new ArrayList<NativeEntry>();
    }

    private List<NativeEntry> selectByIdTemplate(Collection<NativeEntry> coordinatorCollection, CallContext callContext) throws Capi3Exception {
        for (NativeEntry entry : coordinatorCollection) {
            if (entry.getData() instanceof Order) {
                Order order = (Order)entry.getData();

                if (order.getId().equals(idTemplate.getId())) {
                    return Collections.singletonList(entry);
                }
            }
        }

        throw new CountNotMetException(SpaceSelector.SELECTOR_NAME, 0, 0);
    }
}
